let _Vue = null
export default class VueRouter {
  static install(Vue) {
    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true
    _Vue = Vue

    // _Vue.prototype.$router = this.$options.router
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      },
    })
  }
  constructor(options) {
    //option:路由规则
    this.options = options
    //该对象存储的是从options解析过来的路由规则。记录路由组件与组件所在路径的关系
    this.routeMap = {}
    this.data = _Vue.observable({
      current: '/'
    })
  }
  creatRouteMap() {
    this.options.routes.forEach((route) => {
      this.routeMap[route.path] = route.component
    })
  }
  initComponents(Vue) {
    const self = this
    Vue.component('router-link', {
      props: {
        to: String
      },
      render(h) {
        return h("a", {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler(e) {
          history.pushState({},"",this.to)
          this.$router.data.current = this.to
          e.preventDefault();
        }
      },
    })
    Vue.component('router-view', {
      render(h) {
        const comment = self.routeMap[self.data.current]
        return h(comment)
      }
    })
  }
  initEvent() {
    window.addEventListener('popstate',()=>{
      this.data.current = window.location.pathname

    })
  }
  init() {
    this.creatRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }
}